package com.cmol.peopledetectapp.admin;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.cmol.data.GlobalData;
import com.cmol.net.Network;
import com.cmol.peopledetectapp.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Response;

/**
 * 场景管理
 *
 * @author 王国良
 */
public class SceneManageActivity extends AppCompatActivity {
    /**
     * 小数格式转换
     */
    DecimalFormat decimalFormat = new DecimalFormat("##.0%");
    /**
     * 确认操作
     */
    private Button btnOk;
    private RadioButton btnTrue;
    private RadioButton btnClose;
    /**
     * 布局文件
     */
    private TextView currentPeople, occupancy;
    private RadioGroup radioGroup;
    /**
     * 通信模块
     */
    private Network network;
    private String currentSceneID;
    /**
     * 当前人数
     */
    private String peo = new String("");
    /**
     * 当前作为
     */
    private String set = new String("");
    /**
     * 开放状态
     */
    private String opn = new String("");
    private String succeed = new String("");
    /**
     * 状态变量
     */
    private String success = new String("");
    private Double occ = new Double(0);

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scene_manage);
        currentPeople = findViewById(R.id.currentPeople);
        occupancy = findViewById(R.id.occupancy);
        radioGroup = findViewById(R.id.radioGroupState);
        btnOk = findViewById(R.id.buttonOk);
        btnTrue = findViewById(R.id.open);
        btnClose = findViewById(R.id.close);

        init();

        btnOk.setOnClickListener(new OkClickListener());
    }

    /**
     * 从服务器获取信息并进行初始化
     */
    public void init() {

        currentSceneID = GlobalData.getCurrentSceneID() + "";


        // 从服务器得到当前场景信息并赋值给currentScene
        // 打包成Json
        JSONObject tmp = new JSONObject();
        try {
            tmp.put("id", currentSceneID);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        network = new Network(tmp, "/admin/sceneCheck") {
            /**
             * id:
             * peopleNum:
             * seatNum:
             * isOpen:
             */
            @Override
            protected void process(Call call, Response response) throws IOException {
                try {

                    /**
                     * scene : id :
                     *         name :
                     *         open :
                     *         peopleNum :
                     *         seatNum :
                     */
                    // 获取并处理JSON数据
                    final String ans = Objects.requireNonNull(response.body()).string().trim();
                    JSONObject js = new JSONObject(ans);
                    JSONObject cs = js.getJSONObject("scene");
                    peo = cs.getString("peopleNum");
                    set = cs.getString("seatNum");
                    opn = cs.getString("open");
                    occ = Double.valueOf(peo) / Double.valueOf(set);
                    Log.e("peo======================", peo);
                    Log.e("set======================", set);
                    Log.e("opn======================", opn);

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void failureWarn() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(SceneManageActivity.this, "网络请求异常", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        };
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 设置场景信息
        currentPeople.setText(peo);
        occupancy.setText(decimalFormat.format(occ).toString());

        // 设置场景是否开放
        if (opn.equals("true")) {
            btnTrue.setChecked(true);
            btnClose.setChecked(false);
        } else {
            btnTrue.setChecked(false);
            btnClose.setChecked(true);
        }
    }


    /**
     * 监听器，执行对用户是否开放状态的改变
     */
    class OkClickListener implements View.OnClickListener {
        @Override
        public void onClick(View view) {


            if (view.getId() == R.id.buttonOk) {
                // 点的按钮是open时
                if (radioGroup.getCheckedRadioButtonId() == R.id.open) {
                    if (!opn.equals("true")) {
                        // 打包成Json
                        JSONObject tmp = new JSONObject();
                        try {
                            tmp.put("id", GlobalData.getCurrentSceneID() + "");
                            tmp.put("isOpen", true);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        /**
                         * 向服务器上传已经更改开放状态
                         *
                         */
                        network = new Network(tmp, "/admin/sceneAlter") {
                            @Override
                            protected void process(Call call, Response response) throws IOException {
                                String ans = Objects.requireNonNull(response.body()).string().trim();
                                /**
                                 * auth:boolean
                                 */
                                try {
                                    JSONObject js = new JSONObject(ans);
                                    succeed = js.getString("auth");
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }

                            /**
                             * 网络断开
                             */
                            @Override
                            protected void failureWarn() {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(SceneManageActivity.this, "网络请求异常", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        };
                    }

                } else {
                    // 按的按钮是close时
                    if (opn.equals("true")) {
                        // 打包成Json
                        JSONObject tmp = new JSONObject();
                        try {
                            tmp.put("id", GlobalData.getCurrentSceneID() + "");
                            tmp.put("isOpen", false);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        // 向服务器上传已经更改开放状态
                        network = new Network(tmp, "/admin/sceneAlter") {
                            @Override
                            protected void process(Call call, Response response) throws IOException {
                                String ans = Objects.requireNonNull(response.body()).string().trim();
                                /**
                                 * auth:boolean
                                 */
                                try {
                                    JSONObject js = new JSONObject(ans);
                                    success = js.getString("auth");
//                                    if(success) {
//                                        // 提示修改成功
//                                        Toast.makeText(SceneManageActivity.this, "更改成功" , Toast.LENGTH_SHORT).show();
//                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            protected void failureWarn() {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(SceneManageActivity.this, "网络请求异常", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        };
                    }
                }
                //显示提示框
//                Toast.makeText(SceneManageActivity.this, "更改成功" , Toast.LENGTH_SHORT).show();
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
//                e.printStackTrace();
            }
            if (success.equals("true")) {
                // 提示修改成功
                Toast.makeText(SceneManageActivity.this, "更改成功", Toast.LENGTH_SHORT).show();
            }
            if (succeed.equals("true")) {
                // 提示修改成功
                Toast.makeText(SceneManageActivity.this, "更改成功", Toast.LENGTH_SHORT).show();
            }

        }
    }
}